package com.tangyh.basic.sign.util;

import com.tangyh.basic.sign.bean.Doc;
import com.tangyh.basic.sign.bean.Docs;
import com.tangyh.basic.sign.bean.FlowConfigInfo;
import com.tangyh.basic.sign.bean.FlowInfo;
import com.tangyh.basic.sign.bean.PosBean;
import com.tangyh.basic.sign.bean.SignData;
import com.tangyh.basic.sign.bean.SignData.SignDataDetail;
import com.tangyh.basic.sign.bean.Signer;
import com.tangyh.basic.sign.bean.SignerAccount;
import com.tangyh.basic.sign.bean.Signers;
import com.tangyh.basic.sign.bean.Signfield;
import com.tangyh.basic.sign.bean.Signfields;
import com.tangyh.basic.sign.bean.SimpleFormFields;
import com.tangyh.basic.sign.comm.FileBean;
import com.tangyh.basic.sign.enums.EIdentificationType;
import com.tangyh.basic.sign.enums.HeaderConstant;
import com.tangyh.basic.sign.exception.DefineException;
import com.tangyh.basic.sign.factory.Factory;
import com.tangyh.basic.sign.factory.account.CreateOrganizationsByThirdPartyUserId;
import com.tangyh.basic.sign.factory.account.CreatePersonByThirdPartyUserId;
import com.tangyh.basic.sign.factory.account.UpdateOrganizationsByThirdId;
import com.tangyh.basic.sign.factory.base.Account;
import com.tangyh.basic.sign.factory.base.FileTemplate;
import com.tangyh.basic.sign.factory.base.InfoVerify;
import com.tangyh.basic.sign.factory.base.SignFile;
import com.tangyh.basic.sign.factory.filetemplate.CreateTemplateByUploadUrl;
import com.tangyh.basic.sign.factory.filetemplate.CreateTemplateComponents.StructComponentDTO;
import com.tangyh.basic.sign.factory.filetemplate.GetFileUploadUrl;
import com.tangyh.basic.sign.factory.filetemplate.UploadFile;
import com.tangyh.basic.sign.factory.response.ArchiveSignFlowResponse;
import com.tangyh.basic.sign.factory.response.CreateFileByTemplateResponse;
import com.tangyh.basic.sign.factory.response.CreateFlowOneStepResponse;
import com.tangyh.basic.sign.factory.response.CreateOrganizationsByThirdPartyUserIdResponse;
import com.tangyh.basic.sign.factory.response.CreatePersonByThirdPartyUserIdResponse;
import com.tangyh.basic.sign.factory.response.CreateTemplateByUploadUrlResponse;
import com.tangyh.basic.sign.factory.response.CreateTemplateComponentsResponse;
import com.tangyh.basic.sign.factory.response.DownDocumentsResponse;
import com.tangyh.basic.sign.factory.response.GetFileSignUrlResponse;
import com.tangyh.basic.sign.factory.response.GetFileUploadUrlResponse;
import com.tangyh.basic.sign.factory.response.SetSignAuthResponse;
import com.tangyh.basic.sign.factory.response.UpdateOrganizationsByThirdIdResponse;
import com.tangyh.basic.sign.factory.response.UploadFileResponse;
import com.tangyh.basic.sign.factory.response.infoverify.IndividualBaseResponse;
import com.tangyh.basic.sign.factory.signfile.CreateFlowOneStep;
import com.tangyh.basic.sign.factory.signfile.signers.GetFileSignUrl;
import com.tangyh.basic.sign.factory.signfile.signflows.ArchiveSignFlow;
import com.tangyh.basic.sign.properties.SignProperties;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Data
@Slf4j
@Component
@Scope("prototype")
public class SignUtil {

  @Autowired
  private SignProperties signProperties;

  // 项目Id(应用Id）
  private String project_id;
  // 项目密钥(应用密钥）
  private String project_scert;

  @PostConstruct
  public void init() {
    //初始化，传入请求网关，应用id以及密钥,全局一次
    Factory.init(signProperties.getBaseUrl());
  }


  /**
   * @Param: [userId 用户id, name 真实姓名, idNumber 身份证, phone 电话1]
   * @Return: java.lang.String e签宝的用户id
   * @Author: LiXincheng
   * @Description: 创建个人账号
   * @Date:
   */
  public ResultData<String> createPersonAccount(String userId, String name, String idNumber,
      String phone, EIdentificationType type) {
    try {
      log.info("------------------ 创建个人账号 start -----------------");
      log.info("SignUtil.createPersonAccount==>userId=" + userId + "  name=" + name + "  idNumber="
          + idNumber + "  phone=" + phone);
      CreatePersonByThirdPartyUserId createPsn = Account.createPersonByThirdPartyUserId(
          userId,
          name,
          //身份证
          type.getCode(),
          idNumber);
      createPsn.setMobile(phone);
      CreatePersonByThirdPartyUserIdResponse createPsnResp = createPsn
          .execute(project_id, project_scert);
      if (createPsnResp.getCode().equals("53000000")) {
        log.error("------------------ 创建个人账号 异常--》 重复 -----------------");
//        return ResultData.get().setData(createPsnResp.getData().getAccountId()).fail("账户已存在");
        return ResultData.get().setData(createPsnResp.getData().getAccountId());
      }
      if (!createPsnResp.getCode().equals("0")) {
        log.error("------------------ 创建个人账号 异常 -----------------" + createPsnResp.getMessage());
        return ResultData.get().fail(createPsnResp.getMessage());
      }
      log.info("------------------ 创建个人账号 end -----------------");
      String accountId = createPsnResp.getData().getAccountId();
      //静默授权
      if (StringUtils.isEmpty(phone)) {
        ResultData<String> setSignAuthData = setSignAuth(accountId);
        if (!setSignAuthData.getIsSuccess()) {
          return ResultData.get().fail(setSignAuthData.getMessage());
        }
      }

      return ResultData.get().setData(accountId);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.createPersonAccount==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [organizationsId  自己系统的企业id, accountId e的用户id, nameOrg 真实企业名称, idNumberOrg 企业统一社会信用代码]
   * @Return: java.lang.String
   * @Author: LiXincheng
   * @Description:创建企业账号 24742
   * @Date: 2021/11/17 17:43
   */
  public ResultData<String> createOrg(String organizationsId,
      String accountId,
      String nameOrg,
      String idNumberOrg) {
    try {
      log.info("------------------ 创建企业账号 start -----------------");
      log.info(
          "SignUtil.createOrg==>organizationsId=" + organizationsId + "  accountId=" + accountId
              + "  nameOrg=" + nameOrg + "  idNumberOrg=" + idNumberOrg);
      CreateOrganizationsByThirdPartyUserId createOrg = Account
          .createOrganizationsByThirdPartyUserId(
              organizationsId,
              null,
              nameOrg,
              "CRED_ORG_USCC",
              idNumberOrg);
      CreateOrganizationsByThirdPartyUserIdResponse createOrgResp = createOrg
          .execute(project_id, project_scert);
      if (createOrgResp.getCode().equals("53000000")) {
        log.error("------------------ 创建企业账号 异常--》 重复 -----------------");
        return ResultData.get().setData(createOrgResp.getData().getOrgId()).fail("机构已存在");
      }
      if (createOrgResp.getCode().equals("1560102")) {
        log.error("------------------ 创建企业账号 异常--》 重复 -----------------");
        return ResultData.get().fail("统一社会信用代码格式异常");
      }
      if (!createOrgResp.getCode().equals("0")) {
        log.error("------------------ 创建企业账号 异常  -----------------" + createOrgResp.getMessage());
        return ResultData.get().fail(createOrgResp.getMessage());
      }
      String orgId = createOrgResp.getData().getOrgId();
      log.info("------------------ 创建企业账号 end -----------------");
      ResultData<String> setSignAuthData = setSignAuth(orgId);
      if (!setSignAuthData.getIsSuccess()) {
        return ResultData.get().fail(setSignAuthData.getMessage());
      }
      return ResultData.get().setData(orgId);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.createOrg==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [fileList]
   * @Return: void
   * @Author: LiXincheng
   * @Description: 添加doc
   * @Date: 2021/11/26 9:59
   */
  public void createDocs(List<String> fileList) {
    Docs docs = new Docs();
    fileList.forEach(f -> {
      docs.add(new Doc().setFileId(f));
    });
  }

  /**
   * @Param: [fileId, accountId, orgId, signSubject  签署文件标题, psnSignFilePage 页码, psnSignFileX,
   * psnSignFileY, orgSignFilePage, orgSignFileX, orgSignFileY]
   * @Return: com.tangyh.basic.sign.util.ResultData<java.util.Map < java.lang.String,
      * java.lang.String>>
   * @Author: LiXincheng
   * @Description:
   * @Date: 2021/11/19 15:12
   */
  public ResultData<Map<String, String>> b2cSign(
      String accountId,
      String signSubject,
      List<SignData> signDataList, String token, String type, String parkBusinessModel) {
    try {
      log.info("------------------ 一步签署 start -----------------");
      log.info(
          "SignUtil.b2cSign==>" + "  accountId=" + accountId
              + "  signSubject=" + signSubject
//              + " signDataList=" + listToString(signDataList, ",")
      );
      //入参是array格式时，先构造对象参数的array
      Docs docs = new Docs();
      Signers signers = new Signers();
      //flowInfo参数
      FlowInfo flowInfo = new FlowInfo()
          .setBusinessScene(signSubject)
          //启用自动归档
          .setAutoArchive(true)
          //启用自动开启流程
          .setAutoInitiate(true)
          .setInitiatorAccountId(accountId)
          .setInitiatorAuthorizedAccountId(accountId);
      //自由职业者签署的
      if (!StringUtils.isEmpty(parkBusinessModel)&&parkBusinessModel.equals("PLATFORM_SERVICE")) {
        flowInfo.setFlowConfigInfo(new FlowConfigInfo()
            .setNoticeDeveloperUrl(
                signProperties.getFreelanceNoticeDeveloperUrl())
            .setRedirectUrl(signProperties.getFreelanceRedirectUrl() + "?token=" + token)
            .setSignPlatform("1")
            .setNoticeType(""));
      } else {
        flowInfo.setFlowConfigInfo(new FlowConfigInfo()
            .setNoticeDeveloperUrl(
                signProperties.getNoticeDeveloperUrl() + "?successToken=" + token)
            .setRedirectUrl(signProperties.getRedirectUrl() + "?token=" + token + "&type=" + type)
            .setSignPlatform("1")
            .setNoticeType(""));
      }

      signDataList.forEach(p -> {
        docs.add(new Doc().setFileId(p.getFileId()));
        SignDataDetail detail = p.getSignDataDetails().get(0);
        Signfields psnSignfields = createSignfields(p.getFileId(), detail.getSignFilePage()
            , detail.getSignFileX(), detail.getSignFileY(), 0);
        Signer psnSigner = createSigners(0, accountId, psnSignfields);
        signers.add(psnSigner);

        SignDataDetail detail2 = p.getSignDataDetails().get(1);
        if (detail2.getSignFilePage() != 0) {
          Signfields orgSignfields = createSignfields(p.getFileId(), detail2.getSignFilePage()
              , detail2.getSignFileX(), detail2.getSignFileY(), 1);
          Signer orgSigner = createSigners(1, p.getAccountId(), orgSignfields);
          signers.add(orgSigner);
        }

        SignDataDetail detail3 = p.getSignDataDetails().get(2);
        if (detail3.getSignFilePage() != 0) {
          Signfields orgSignfields = createSignfields(p.getFileId(), detail3.getSignFilePage()
              , detail3.getSignFileX(), detail3.getSignFileY(), 2);
          Signer orgSigner = createSigners(2, p.getOrgId(), orgSignfields);
          signers.add(orgSigner);
        }
      });

      CreateFlowOneStep flowOneStep = SignFile.createFlowOneStep(docs, flowInfo, signers);
      CreateFlowOneStepResponse flowOneStepResp = flowOneStep.execute(project_id, project_scert);
      if (!flowOneStepResp.getCode().equals("0")) {
        log.error("------------------ 一步发起签署 异常 -----------------" + flowOneStepResp.getMessage());
        return ResultData.get().fail(flowOneStepResp.getMessage());
      }
      //流程id保存好
      String flowId = flowOneStepResp.getData().getFlowId();

      log.info("------------------ 获取签署地址 start -----------------");
      GetFileSignUrl fileSignUrl = SignFile.getFileSignUrl(flowId, accountId);
      GetFileSignUrlResponse fileSignUrlResp = fileSignUrl.execute(project_id, project_scert);
      if (!fileSignUrlResp.getCode().equals("0")) {
        log.error("------------------ 获取签署地址 异常 -----------------" + fileSignUrlResp.getMessage());
        return ResultData.get().fail(fileSignUrlResp.getMessage());
      }
      //响应的签署链接，复制到浏览器访问即可打开签署页面
      String shortUrl = fileSignUrlResp.getData().getShortUrl();
      log.info("签署短连接,复制到浏览器打开\n" + shortUrl);
      log.info("------------------ 获取签署地址 end -----------------");

      log.info("------------------ 一步签署 end -----------------");

      Map<String, String> map = new HashMap<>();
      map.put("flowId", flowId);
      map.put("shortUrl", shortUrl);
      return ResultData.get().setData(map);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.b2cSign==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  public Signfields createSignfields(String fileId, int psnSignFilePage, int psnSignFileX,
      int psnSignFileY, int type) {
    //构造个人signfields参数对象,用于后续入参使用,支持链式入参
    Signfield signfield = new Signfield()
        .setFileId(fileId)
        .setPosBean(new PosBean()
            .setPosPage(psnSignFilePage + "")
            .setPosX(psnSignFileX)
            .setPosY(psnSignFileY))
        .setSignDateBeanType(0);
    if (type == 1) {
      signfield
          .setAutoExecute(true);
    } else if (type == 2) {
      signfield
          .setActorIndentityType("2")
          .setAutoExecute(true);
    }
    Signfields signfields = new Signfields();
    signfields.add(signfield);
    return signfields;
  }

  public Signer createSigners(Integer type, String id, Signfields signfields) {
    Signer signer = null;
    switch (type) {
      //个人
      case 0:
        signer = new Signer()
            .setSignerAccount(
                new SignerAccount()
                    .setSignerAccountId(id)
            )
            //传入个人signer信息
            .setSignFields(signfields).setSignOrder(3);
        break;
      //法人
      case 1:
        signer = new Signer()
            .setSignerAccount(
                new SignerAccount()
                    .setSignerAccountId(id)
            )
            //传入个人signer信息
            .setSignFields(signfields).setSignOrder(1);
        break;
      //公司
      case 2:
        signer = new Signer()
            .setSignerAccount(
                new SignerAccount()
                    //签署经办人
                    .setSignerAccountId(id)
                    //企业签署需要传入该参数
                    .setAuthorizedAccountId(id)
                //传入企业signer信息
            ).setSignFields(signfields).setSignOrder(2);
        break;
      default:
        signer = new Signer();
        break;
    }
    return signer;
  }

  /**
   * @Param: [filePath]
   * @Return: com.tangyh.basic.sign.util.ResultData<java.lang.String>
   * @Author: LiXincheng
   * @Description: 上传模板
   * @Date: 2021/11/22 17:56
   */
  public ResultData<Map<String, String>> uploadSignTemplate(MultipartFile multipartFile) {
    try {
      log.info("------------------ 通过上传方式创建模板 start -----------------");
      log.info("SignUtil.uploadSignTemplate==>multipartFile=" + multipartFile);
      //cn.tign.hz.factory.base.FileTemplate;
      //FileTemplate是文件模板功能类，所有文件模板相关的接口由FileTemplate发起
      //用于本地获取文件大小，名称等信息
      FileBean fileBean = new FileBean(multipartFile);
      CreateTemplateByUploadUrl fileUploadUrl = FileTemplate
          .createTemplateByUploadUrl(fileBean.getFileContentMD5(),
              HeaderConstant.CONTENTTYPE_PDF.VALUE(),
              fileBean.getFileName(),
              false);
      CreateTemplateByUploadUrlResponse fileUploadUrlResp = fileUploadUrl
          .execute(project_id, project_scert);
      if (!fileUploadUrlResp.getCode().equals("0")) {
        log.error(
            "------------------ 通过上传方式创建模板 异常 -----------------" + fileUploadUrlResp.getMessage());
        return ResultData.get().fail(fileUploadUrlResp.getMessage());
      }
      Map<String, String> map = new HashMap<>();
      //文件id保存好，后续使用
      String templateId = fileUploadUrlResp.getData().getTemplateId();
      //上传url保存好，后续使用
      String uploadUrl = fileUploadUrlResp.getData().getUploadUrl();
      map.put("templateId", templateId);
      map.put("uploadUrl", uploadUrl);
      log.info("------------------ 通过上传方式创建文件 end -----------------");

      log.info("------------------ 文件流上传方法 start -----------------");
      UploadFile uploadFile = FileTemplate
          .uploadFile(uploadUrl, multipartFile, HeaderConstant.CONTENTTYPE_PDF.VALUE());
      UploadFileResponse uploadFileResp = uploadFile.excuteByStream();
      if (uploadFileResp.getStatus() != 200) {
        log.error("SignUtil.uploadSignTemplate==>e=" + uploadFileResp.getBody());
        return ResultData.get().fail("uploadSignTemplate文件流上传异常");
      }
      log.info("------------------ 文件流上传方法 end -----------------");

      return ResultData.get().setData(map);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("SignUtil.uploadSignTemplate==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  public ResultData<Map<String, String>> uploadImage(String filePath) {
    try {
      log.info("------------------ 上传图片 start -----------------");
      log.info("SignUtil.uploadImage==>filePath=" + filePath);
      //cn.tign.hz.factory.base.FileTemplate;
      //FileTemplate是文件模板功能类，所有文件模板相关的接口由FileTemplate发起
      //用于本地获取文件大小，名称等信息
      FileBean fileBean = new FileBean(filePath);
      GetFileUploadUrl fileUploadUrl = FileTemplate
          .getFileUploadUrl(fileBean.getFileContentMD5(),
              HeaderConstant.CONTENTTYPE_STREAM.VALUE(),
              false,
              fileBean.getFileName(),
              fileBean.getFileSize());
      GetFileUploadUrlResponse fileUploadUrlResp = fileUploadUrl
          .execute(project_id, project_scert);
      if (!fileUploadUrlResp.getCode().equals("0")) {
        log.error(
            "------------------ 上传图片 异常 -----------------" + fileUploadUrlResp.getMessage());
        return ResultData.get().fail(fileUploadUrlResp.getMessage());
      }
      Map<String, String> map = new HashMap<>();
      //文件id保存好，后续使用
      String fileId = fileUploadUrlResp.getData().getFileId();
      //上传url保存好，后续使用
      String uploadUrl = fileUploadUrlResp.getData().getUploadUrl();
      map.put("fileId", fileId);
      map.put("uploadUrl", uploadUrl);
      log.info("------------------ 上传图片 end -----------------");

      log.info("------------------ 文件流上传方法 start -----------------");
      UploadFile uploadFile = FileTemplate
          .uploadFile(uploadUrl, filePath, HeaderConstant.CONTENTTYPE_STREAM.VALUE());
      UploadFileResponse uploadFileResp = uploadFile.excute();
      if (uploadFileResp.getStatus() != 200) {
        log.error("SignUtil.uploadImage==>e=" + uploadFileResp.getBody());
        return ResultData.get().fail("uploadImage文件流上传异常");
      }
      log.info("------------------ 文件流上传方法 end -----------------");

      return ResultData.get().setData(map);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("SignUtil.uploadImage==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  @Deprecated
  public ResultData<String> uploadSignTemplate(String filePath) {
    try {
      log.info("------------------ 通过上传方式创建模板 start -----------------");
      log.info("SignUtil.uploadSignTemplate==>filePath=" + filePath);
      //cn.tign.hz.factory.base.FileTemplate;
      //FileTemplate是文件模板功能类，所有文件模板相关的接口由FileTemplate发起
      //用于本地获取文件大小，名称等信息
      FileBean fileBean = new FileBean(filePath);
      CreateTemplateByUploadUrl fileUploadUrl = FileTemplate
          .createTemplateByUploadUrl(fileBean.getFileContentMD5(),
              HeaderConstant.CONTENTTYPE_PDF.VALUE(),
              fileBean.getFileName(),
              false);
      CreateTemplateByUploadUrlResponse fileUploadUrlResp = fileUploadUrl
          .execute(project_id, project_scert);
      if (!fileUploadUrlResp.getCode().equals("0")) {
        log.error(
            "------------------ 通过上传方式创建模板 异常 -----------------" + fileUploadUrlResp.getMessage());
        return ResultData.get().fail(fileUploadUrlResp.getMessage());
      }
      //文件id保存好，后续使用
      String templateId = fileUploadUrlResp.getData().getTemplateId();
      //上传url保存好，后续使用
      String uploadUrl = fileUploadUrlResp.getData().getUploadUrl();
      log.info("------------------ 通过上传方式创建文件 end -----------------");

      log.info("------------------ 文件流上传方法 start -----------------");
      UploadFile uploadFile = FileTemplate
          .uploadFile(uploadUrl, filePath, HeaderConstant.CONTENTTYPE_PDF.VALUE());
      UploadFileResponse uploadFileResp = uploadFile.excute();
      if (uploadFileResp.getStatus() != 200) {
        log.error("SignUtil.uploadSignTemplate==>e=" + uploadFileResp.getBody());
        return ResultData.get().fail("uploadSignTemplate文件流上传异常");
      }
      log.info("------------------ 文件流上传方法 end -----------------");

      return ResultData.get().setData(templateId);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.uploadSignTemplate==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [templateId 模板id, fileName 文件名, simpleFormFields  数据]
   * @Return: com.tangyh.basic.sign.util.ResultData<java.lang.String>
   * @Author: LiXincheng
   * @Description: 模板配置数据
   * @Date: 2021/11/22 17:56
   */
  public ResultData<String> configurationTemplate(String templateId, String fileName,
      SimpleFormFields simpleFormFields) {
    try {
      log.info("------------------ 配置模板数据 start -----------------");
      log.info(
          "SignUtil.configurationTemplate==>templateId=" + templateId + "  fileName=" + fileName
              + "  simpleFormFields=" + simpleFormFields);
//    SimpleFormFields simpleFormFields  =new SimpleFormFields();
//    simpleFormFields.put("Text1","aaaaa");
//    simpleFormFields.put("Text2","bbbbb");
      CreateFileByTemplateResponse createFileByTemplateResponse = FileTemplate
          .createFileByTemplate(fileName, templateId, simpleFormFields)
          .execute(project_id, project_scert);
      if (!createFileByTemplateResponse.getCode().equals("0")) {
        log.error("------------------ 配置模板数据 异常 -----------------" + createFileByTemplateResponse
            .getMessage());
        return ResultData.get().fail(createFileByTemplateResponse.getMessage());
      }
      String fileId = createFileByTemplateResponse.getData().getFileId();
      log.info("------------------ 配置模板数据 end -----------------");
      return ResultData.get().setData(fileId);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.configurationTemplate==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [orgId] 机构id
   * @Return: com.tangyh.basic.sign.util.ResultData<java.lang.String>
   * @Author: LiXincheng
   * @Description:机构静默签署权限
   * @Date: 2021/11/22 17:55
   */
  public ResultData<String> setSignAuth(String orgId) {
    try {
      log.info("------------------ 设置静默签署授权 end -----------------");
      log.info("SignUtil.setSignAuth==>orgId=" + orgId);
      SetSignAuthResponse setSignAuthResponse = Account.setSignAuth(orgId)
          .execute(project_id, project_scert);
      if (!setSignAuthResponse.getCode().equals("0")) {
        log.error(
            "------------------ 设置静默签署授权 异常 -----------------" + setSignAuthResponse.getMessage());
        return ResultData.get().fail(setSignAuthResponse.getMessage());
      }
      log.info("------------------ 设置静默签署授权 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.setSignAuth==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [filePath  本地文件地址]
   * @Return: com.tangyh.basic.sign.util.ResultData<java.lang.String>
   * @Author: LiXincheng
   * @Description: 1：获取文件上传地址  2：文件流上传
   * @Date: 2021/11/18 10:19
   */
  @Deprecated
  public ResultData<Map<String, String>> uploadSignFile(String filePath) {
    try {
      log.info("------------------ 通过上传方式创建文件 start -----------------");
      log.info("SignUtil.uploadSignFile==>filePath=" + filePath);
      //cn.tign.hz.factory.base.FileTemplate;
      //FileTemplate是文件模板功能类，所有文件模板相关的接口由FileTemplate发起
      FileBean fileBean = new FileBean(filePath);//用于本地获取文件大小，名称等信息
      GetFileUploadUrl fileUploadUrl = FileTemplate.getFileUploadUrl(fileBean.getFileContentMD5(),
          HeaderConstant.CONTENTTYPE_PDF.VALUE(),
          false,
          fileBean.getFileName(),
          fileBean.getFileSize());
      GetFileUploadUrlResponse fileUploadUrlResp = fileUploadUrl.execute(project_id, project_scert);
      if (!fileUploadUrlResp.getCode().equals("0")) {
        log.error(
            "------------------ 通过上传方式创建文件 异常 -----------------" + fileUploadUrlResp.getMessage());
        return ResultData.get().fail(fileUploadUrlResp.getMessage());
      }
      String fileId = fileUploadUrlResp.getData().getFileId();//文件id保存好，后续使用
      String uploadUrl = fileUploadUrlResp.getData().getUploadUrl();//上传url保存好，后续使用
      log.info("------------------ 通过上传方式创建文件 end -----------------");

      log.info("------------------ 文件流上传方法 start -----------------");
      UploadFile uploadFile = FileTemplate
          .uploadFile(uploadUrl, filePath, HeaderConstant.CONTENTTYPE_PDF.VALUE());
      UploadFileResponse uploadFileResp = uploadFile.excute();
      if (uploadFileResp.getStatus() != 200) {
        log.error("SignUtil.uploadSignFile==>e=" + uploadFileResp.getBody());
        return ResultData.get().fail("uploadSignFile文件流上传异常");
      }
      log.info("------------------ 文件流上传方法 end -----------------");
      Map<String, String> map = new HashMap<>(2);
      map.put("fileId", fileId);
      map.put("uploadUrl", uploadUrl);
      return ResultData.get().setData(map);
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.uploadSignFile==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [flowId]
   * @Return: com.tangyh.basic.sign.util.ResultData<java.util.List>
   * @Author: LiXincheng
   * @Description: 下载合同
   * @Date: 2021/11/18 15:04
   */
  public ResultData<com.tangyh.basic.sign.factory.response.other.Docs> downloadFile(String flowId) {
    try {
      log.info("------------------ 下载合同 start -----------------");
      log.info("SignUtil.downloadFile==>flowId=" + flowId);
      DownDocumentsResponse response = SignFile.downDocuments(flowId)
          .execute(project_id, project_scert);
      if (!response.getCode().equals("0")) {
        log.error("------------------ 下载合同 异常 -----------------" + response.getMessage());
        return ResultData.get().fail(response.getMessage());
      }
      log.info("------------------ 下载合同 end -----------------");
      return ResultData.get().setData(response.getData().getDocs());
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.downloadFile==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [organizationsId, orgName, orgNum, orgLegalName, orgLegalIdNumber]
   * @Return: com.tangyh.basic.sign.util.ResultData
   * @Author: LiXincheng
   * @Description: 修改机构账户信息
   * @Date: 2021/11/23 10:51
   */
  @Deprecated
  public ResultData editOrgAccount(String organizationsId, String orgName,
      String orgNum, String orgLegalName, String orgLegalIdNumber) {
    try {
      log.info("------------------ 修改机构账户信息 start -----------------");
      log.info(
          "SignUtil.editOrgAccount==>organizationsId=" + organizationsId + " orgName=" + orgName
              + " orgNum=" + orgNum
              + " orgLegalName=" + orgLegalName + " orgLegalIdNumber=" + orgLegalIdNumber);
      UpdateOrganizationsByThirdId updateOrganizationsByThirdId = Account
          .updateOrganizationsByThirdId(organizationsId);
      updateOrganizationsByThirdId.setName(orgName);
      updateOrganizationsByThirdId.setIdNumber(orgNum);
      updateOrganizationsByThirdId.setOrgLegalName(orgLegalName);
      updateOrganizationsByThirdId.setOrgLegalIdNumber(orgLegalIdNumber);
      UpdateOrganizationsByThirdIdResponse updateOrganizationsByThirdIdResponse = updateOrganizationsByThirdId
          .execute(project_id, project_scert);
      if (!updateOrganizationsByThirdIdResponse.getCode().equals("0")) {
        log.error(
            "------------------ 修改机构账户信息 异常 -----------------"
                + updateOrganizationsByThirdIdResponse
                .getMessage());
        return ResultData.get().fail(updateOrganizationsByThirdIdResponse.getMessage());
      }
      log.info("------------------ 修改机构账户信息 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.editOrgAccount==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  @Deprecated
  public ResultData editOrgAccount(String organizationsId, String orgName,
      String orgNum, String accountId) {
    try {
      log.info("------------------ 修改机构账户信息 start -----------------");
      log.info(
          "SignUtil.editOrgAccount==>organizationsId=" + organizationsId + " orgName=" + orgName
              + " orgNum=" + orgNum
              + " accountId=" + accountId);
      UpdateOrganizationsByThirdId updateOrganizationsByThirdId = Account
          .updateOrganizationsByThirdId(organizationsId);
      updateOrganizationsByThirdId.setName(orgName);
      updateOrganizationsByThirdId.setIdNumber(orgNum);
      updateOrganizationsByThirdId.setCreator(accountId);
      UpdateOrganizationsByThirdIdResponse updateOrganizationsByThirdIdResponse = updateOrganizationsByThirdId
          .execute(project_id, project_scert);
      if (updateOrganizationsByThirdIdResponse.getCode().equals("53000003")) {
        log.error(
            "------------------ 修改机构账户信息 异常 -----------------"
                + updateOrganizationsByThirdIdResponse
                .getMessage());
        return ResultData.get().fail("e签宝统一社会信用代码已经存在");
      }
      if (!updateOrganizationsByThirdIdResponse.getCode().equals("0")) {
        log.error(
            "------------------ 修改机构账户信息 异常 -----------------"
                + updateOrganizationsByThirdIdResponse
                .getMessage());
        return ResultData.get().fail(updateOrganizationsByThirdIdResponse.getMessage());
      }
      log.info("------------------ 修改机构账户信息 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.editOrgAccount==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [flowId]
   * @Return: com.tangyh.basic.sign.util.ResultData
   * @Author: LiXincheng
   * @Description: 归档
   * @Date: 2021/11/18 15:48
   */
  @Deprecated
  public ResultData archiveSignFlow(String flowId) {
    try {
      //全部签署完成以后进行归档，归档以后就不能再修改了
      log.info("------------------ 签署流程归档 start -----------------");
      log.info("SignUtil.archiveSignFlow==>flowId=" + flowId);
      ArchiveSignFlow archiveSignFlow = SignFile.archiveSignFlow(flowId);
      ArchiveSignFlowResponse response = archiveSignFlow.execute(project_id, project_scert);
      if (!response.getCode().equals("0")) {
        log.error("------------------ 签署流程归档 异常 -----------------" + response.getMessage());
        return ResultData.get().fail(response.getMessage());
      }
      log.info("------------------ 签署流程归档 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.archiveSignFlow==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [name, idNo]
   * @Return: com.tangyh.basic.sign.util.ResultData
   * @Author: LiXincheng
   * @Description: 个人二要素认证
   * @Date: 2021/11/19 15:32
   */
  public ResultData psn2Verify(String name, String idNo) {
    try {
      log.info("------------------ 个人2要素信息比对 start -----------------");
      log.info("SignUtil.psn2Verify==>name=" + name + " idNo=" + idNo);
      IndividualBaseResponse infoVerify = InfoVerify.individualBase(idNo, name)
          .execute(project_id, project_scert);
      if (!infoVerify.getCode().equals("0")) {
        log.error("------------------ 个人2要素信息比对 异常 -----------------" + infoVerify.getMessage());
        return ResultData.get().fail(infoVerify.getMessage());
      }
      log.info("------------------ 个人2要素信息比对 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.psn2Verify==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  /**
   * @Param: [structComponent, templateId]
   * @Return: com.tangyh.basic.sign.util.ResultData
   * @Author: LiXincheng
   * @Description: 模板添加控件
   * @Date: 2021/12/7 17:39
   */
  public ResultData createTemplateComponents(List<StructComponentDTO> structComponent,
      String templateId) {
    try {
      log.info("------------------ e签宝模板添加控件 start -----------------");
      log.info(
          "SignUtil.createTemplateComponents==>structComponent=" + listToString(structComponent,
              ","));
      CreateTemplateComponentsResponse response = FileTemplate
          .createTemplateComponents(structComponent, templateId).execute(project_id, project_scert);
      if (response.getStatus() != 0) {
        log.error("------------------ e签宝模板添加控件 异常 -----------------" + response.getMessage());
        return ResultData.get().fail(response.getMessage());
      }
      log.info("------------------ e签宝模板添加控件 end -----------------");
      return ResultData.get();
    } catch (DefineException e) {
      e.printStackTrace();
      log.error("SignUtil.createTemplateComponents==>e=" + e.getMessage());
      return ResultData.get().fail(e.getMessage());
    }
  }

  public String listToString(List list, String separator) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
      sb.append(list.get(i)).append(separator);
    }
    return sb.toString().substring(0, sb.toString().length() - 1);
  }


}